package com.lntea.netty.demo.diff.echo.bio;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Title: BioEcho.java<br>
 * Description:  阻塞网络类型服务端<br>
 * Copyright: Copyright (c) 2015<br>
 * Company: 北京云杉世界信息技术有限公司<br>
 *
 * @author lichao
 * @date 2019/11/4 10:35
 */
public class BioEcho {

    /** server ip */
    private final String SERVER_IP = "127.0.0.1";
    /** server port */
    private Integer SERVER_PORT = 8080;
    /** 查询时间约定字符串 */
    private final String QUERY_TIME = "query_time";

    @Test
    public void startEchoServer() {
        try (ServerSocket serverSocket = new ServerSocket(SERVER_PORT)) {
            System.out.println(String.format("The Echo Server start in port %d", SERVER_PORT));

            while (true) {
                Socket socket = serverSocket.accept();
                new Thread(new BioEchoServerHandler(socket, QUERY_TIME)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("The Echo Server close");
        }
    }

    @Test
    public void startEchoClient() {
        try (Socket socket = new Socket(SERVER_IP, SERVER_PORT);
             BufferedReader inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             PrintWriter outputWriter = new PrintWriter(socket.getOutputStream(), true)) {

            outputWriter.println(QUERY_TIME);
            System.out.println("echo client request time");
            String timeStr = inputReader.readLine();
            System.out.println(String.format("echo client accept server time : %s", timeStr));
            outputWriter.println("");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
